/**
 * @name: webSocket封装
 * @date: 2020.4.10
 */
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

var _this = new Vue();

const socket = new Vuex.Store({
	state: {
		link: null,
		isdidPage: false, // 是否是加注完成页面
		timer: '',
		hasTimer: false, // 是否有定时器
		socketMsgQueue: [

		]
	},
	mutations: {
		//创建连接
		linkInit(state, token) {
			state.link = uni.connectSocket({
				url: _this.$api.socketUrl + '?token=' + token,
				complete: () => {}
			});
			state.link.onOpen(() => {
				console.log('连接已打开！');
				if (state.hasTimer) {
					clearInterval(state.timer);
					state.hasTimer = false;
				}
			});
			state.link.onClose(() => {
				console.log('连接已关闭！');
				this.dispatch('check');
			});
			state.link.onError(() => {
				console.log('连接打开失败，请检查！');
				if (getApp().globalData.timer && !state.hasTimer) {
					state.timer = setInterval(() => {
						this.dispatch('check');
					}, 1000);
					state.hasTimer = true;
				}
			});
			state.link.onMessage(obj => {
				let res = JSON.parse(obj.data);
				console.log('socket.js', res);
				// 如果token过期，提示重新登录
				if (res.msgtype === "auth" && !res.data.success) {
					_this.$store.commit('logout');
					_this.$store.commit('showLogin', true);
				} else {
					if (res.msgtype === 'filled') {
						res.showMsg = true;
						const pages = getCurrentPages();
						const currentPage = pages[pages.length - 1];
						const path = currentPage.$page.fullPath;
						
						// 加注完成如果当前页不是加注完成页面就跳转到加注完成页面
						if (path.indexOf('did') === -1) {
							uni.navigateTo({
								url:'/pages/fill/did'
							})
						}
						this.commit('addMsgQueue', {
							msgItem: res
						});
					}
					uni.$emit('linkListen', res);
				}
			});
		},
		//发送数据
		linkSend(state, msg) {
			state.link.send({
				data: msg
			});
		},
		//关闭连接
		linkClose(state) {
			if (state.link) {
				state.link.close();
			}
		},
		// 关闭某一个socket消息
		closeMsg(state, {
			index
		}) {
			if (index == -1) {
				state.socketMsgQueue = [];
			} else {
				_this.$set(state.socketMsgQueue[index], 'showMsg', false);
			}
		},
		// 显示某一个socket消息
		openMsg(state, {
			index
		}) {
			_this.$set(state.socketMsgQueue[index], 'showMsg', true);
		},
		// 插入消息队列
		addMsgQueue(state, {
			msgItem
		}) {
			console.log(msgItem);
			state.socketMsgQueue.splice(0, 1, msgItem);
			_this.$store.commit('setTmpData', JSON.stringify(msgItem.data));
		},
		changeIsdidPage(state, {
			status
		}) {
			state.isdidPage = status;
		}
	},
	getters: {

	},
	actions: {
		init({
			commit
		}) {
			let token = uni.getStorageSync(_this.$tmp.TOKEN_INFO);
			if (token) commit('linkInit', token);
		},
		send({
			commit
		}, msg) {
			commit('linkSend', msg);
		},
		close({
			commit
		}) {
			commit('linkClose');
		},
		//检测连接是否正常，closing 或 closed 状态下重新连接
		check({
			commit
		}) {
			console.log('检测连接是否正常');
			let token = _this.$store.state.token;
			if (token) {
				console.log(socket.state.link);
				if (!socket.state.link) {
					console.log(socket.state.link);
					commit('linkInit', token);
				} else {
					if (socket.state.link.readyState === 1) {
						console.log('已经连接');
						// commit('linkSend', '{msgtype:"ping",data:{{"ping": 1}}}');
					} else {
						console.log('重新初始化');
						commit('linkInit', token);
					}
				}
			}
		}
	}
})

Vue.prototype.$socket = socket;
